package com.zmytest.aop;

import com.zmytest.annotation.CreateSession;
import com.zmytest.service.SessionService;
import com.zmytest.util.ConfigAnalyzer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * Created on 2018/12/21.
 *
 * @author zhangmingyu
 */
@Aspect
@Component
@Slf4j
public class CreateSessionAspect {

    private final SessionService sessionService;

    public CreateSessionAspect(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    @Pointcut(value = "@annotation(com.zmytest.annotation.CreateSession)")
    public void pointCut(){}

    @AfterReturning(returning = "result",pointcut = "pointCut() && @annotation(createSession)")
    public void afterReturnning(JoinPoint joinPoint, Object result, CreateSession createSession){
        String flagConfigStr = createSession.flag();
        if (ObjectUtils.isEmpty(flagConfigStr)) {
            createSession(joinPoint,result,createSession);
            return;
        }
        Object realFlag = ConfigAnalyzer.getValue(joinPoint,result,flagConfigStr);
        Object realFlagConfigResult = getFlagConfigResult(joinPoint,result,createSession.flagResult());
        if (realFlagConfigResult.equals(realFlag)) {
            createSession(joinPoint,result,createSession);
        }
    }

    private Object getFlagConfigResult(JoinPoint joinPoint, Object result, String flagResultConfigStr){
        Object realFlagResult = Boolean.TRUE;
        if (!ObjectUtils.isEmpty(flagResultConfigStr)){
            realFlagResult = ConfigAnalyzer.getValue(joinPoint,result,flagResultConfigStr);
        }
        return realFlagResult;
    }

    private void createSession(JoinPoint joinPoint,Object result, CreateSession createSession){
        String key = createSession.key();
        String value = createSession.value();
        String realKey = ConfigAnalyzer.getValue(joinPoint,result,key).toString();
        Object realValue = ConfigAnalyzer.getValue(joinPoint,result,value);
        sessionService.create(realKey,realValue);
    }
}
